package com.tju.resource.tool.tool;

import cn.hutool.http.HttpRequest;
import cn.hutool.http.HttpUtil;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;

import java.net.*;
import java.text.DecimalFormat;
import java.util.Enumeration;

/**
 * IP工具
 *
 * @USER: CLS
 */
@Slf4j
public class IpUtil {

    public static final String IP_TEST_URL = "https://ds.jp2.test-ipv6.com/ip/?callback=_jqjsp&testdomain=test-ipv6.com&testname=test_ds";
    public static final String IP_TEST_URL_HOST = "ds.jp2.test-ipv6.com";

    /**
     * 查找所有网络接口
     */
    public static void printAllIp() {
        try {
            Enumeration<NetworkInterface> allNetInterfaces = NetworkInterface.getNetworkInterfaces();
            while (allNetInterfaces.hasMoreElements()) {
                NetworkInterface netInterface = allNetInterfaces.nextElement();

                // Remove loopback interface, sub-interface, unrun and interface
                if (netInterface.isLoopback() || netInterface.isVirtual() || !netInterface.isUp()) {
                    continue;
                }

                Enumeration<InetAddress> addresses = netInterface.getInetAddresses();
                while (addresses.hasMoreElements()) {
                    InetAddress ip = addresses.nextElement();
                    if (ip != null) {

                        // ipv4
                        if (ip instanceof Inet4Address) {

                            if (!ip.getHostAddress().startsWith("192") && !ip.getHostAddress().startsWith("10") && !ip.getHostAddress().startsWith("172")) {
                                // Intranet
                                ip.getHostAddress();
                            }
                        }
                    }
                }
            }
        } catch (SocketException e) {
        }
    }

    /**
     * 获取 (IP4) 的ip
     *
     * @return
     */
    public static String getHostIP() {
        try {
            // 根据 hostname 找 ip
            InetAddress address = InetAddress.getLocalHost();
            if (address.isLoopbackAddress()) {
                Enumeration<NetworkInterface> allNetInterfaces = NetworkInterface.getNetworkInterfaces();
                while (allNetInterfaces.hasMoreElements()) {
                    NetworkInterface netInterface = allNetInterfaces.nextElement();
                    Enumeration<InetAddress> addresses = netInterface.getInetAddresses();
                    while (addresses.hasMoreElements()) {
                        InetAddress ip = addresses.nextElement();
                        if (!ip.isLinkLocalAddress() && !ip.isLoopbackAddress() && ip instanceof Inet4Address) {
                            return ip.getHostAddress();
                        }
                    }
                }
            }
            return address.getHostAddress();
        } catch (UnknownHostException | SocketException e) {
            e.printStackTrace();
            return null;
        }
    }

    /**
     * 获取服务器名称
     *
     * @return
     */
    public static String getHostName() {
        try {
            InetAddress localhost = InetAddress.getLocalHost();
            return localhost.getHostName();
        } catch (Exception e) {
            log.error(e.getMessage());
            return e.getMessage();
        }
    }

    /**
     * Get public ipv4 address
     */
    public static String getIpv4OnNet() {
        HttpRequest get = HttpUtil.createGet(IP_TEST_URL);
        String response;

        get.header("Cache-Control", "no-cache");
        get.header("Host", IP_TEST_URL_HOST);
        response = get.execute().body();

        if (StringUtils.isBlank(response)) {
            return "unknown";
        } else {
            response = response.replace(response.substring(response.indexOf('_'), response.indexOf('(') + 1), "").replace(")", "").replace("\n", "");

            if (JSONUtil.isJsonObj(response)) {
                return JSONUtil.parseObj(response).getStr("ip");
            } else {
                return "unknown";
            }

        }
    }

//
//    /**
//     * 计算磁盘使用率
//     *
//     * @param num1
//     * @param num2
//     * @return
//     */
//    public static Integer bfb(Object num1, Object num2) {
//        double val1 = Double.valueOf(num1.toString());
//        double val2 = Double.valueOf(num2.toString());
//        if (val2 == 0) {
//            return 0;
//        } else {
//            DecimalFormat df = new DecimalFormat("#0.00");
//            return new Double(Math.ceil(val1 / val2 * 100)).intValue();
//        }
//    }
}